<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <!-- <el-col :xs="8" :sm="6" :md="8" :lg="5"> -->
        <el-form-item>
          <el-tooltip class="item" effect="dark" content="申请时间" placement="top">
            <el-date-picker size="small" style="width:200px;" v-model="filters.Time" type="daterange" align="left" placeholder="请选择申请时间范围">
            </el-date-picker>
          </el-tooltip>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :xs="8" :sm="4" :md="4" :lg="3"> -->
        <!-- <el-form-item>
          <el-input size="small" style="width:200px;" v-model.trim="filters.userId" placeholder="用户ID"></el-input>
        </el-form-item> -->
        <!-- </el-col> -->
        <!-- <el-col :xs="8" :sm="6" :md="4" :lg="4"> -->
        <el-form-item>
          <el-select size="small" clearable style="width:200px;" v-model="filters.status" placeholder="状态">
            <!-- <el-option  label="全部风险等级"  value="-1"  ></el-option> -->
            <el-option label="已发放" value="1"></el-option>
            <el-option label="待审批" value="2"></el-option>
            <el-option label="审批未通过" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-form-item style="float:right;">
          <el-button size="small" class="button_style" type="primary" icon="upload2" @click="exportExcels">导出</el-button>
        </el-form-item> -->
        <el-form-item style="float:right;">
          <el-button size="small" type="primary" icon="plus" v-show="handAdd" :disabled="configUser()" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item style="float:right;">
          <el-button size="small" class="button_style" v-show="handQuery" type="primary" icon="search" v-on:click="getGives(true)">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="Logs" stripe border :height="winHeight-188" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <!-- <el-table-column type="selection" width="55">
      </el-table-column> -->
      <!-- <el-table-column prop="serialNo" label="序号" width="120" sortable>
      </el-table-column> -->
      <el-table-column prop="id" label="发放ID" align="center" width="100">
      </el-table-column>
      <el-table-column prop="totalScore" label="发放数量" align="center" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="people" label="发放人数" align="center" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请发放时间" min-width="150" align="center" sortable>
      </el-table-column>
      <el-table-column prop="approveTime" align="center" min-width="150" label="实际发放时间" sortable>
      </el-table-column>
      <el-table-column prop="status" align="center" min-width="80" label="状态" :formatter="formatStatus">
      </el-table-column>
      <el-table-column prop="remark" align="center" min-width="120" label="发放说明" show-overflow-tooltip>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed='right' width="150">
        <template scope="scope">
          <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button> -->
          <!-- <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button> -->
          <el-col :xs="12" :sm="12" :md="12" :lg="12">
            <el-button size="small" v-show="handDetail" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
          </el-col>
          <el-col :xs="12" :sm="12" :md="12" :lg="12">
            <el-button type="danger" size="small" :disabled="ApproveUser(scope.$index,scope.row)" v-show="IsExamines(scope.$index, scope.row)" @click="handleExamine(scope.$index, scope.row)">审批</el-button>
          </el-col>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->

      <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>
    <!--新增界面-->
    <el-dialog title="新增发放" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form label-width="125px" :model="addForm" :rules="addFormRules" ref="addForm">
        <el-form-item label="发放明细:" prop="activityScript">
          <el-upload ref="upload" :action="picURL" :on-change="Isupload" :on-success="handleSuccess" :file-list="fileList" :auto-upload="false" :data="{parampath:handworkvalue,remark:addForm.remark}">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="float:right;" size="small" type="warning" @click="download(true)">下载明细模版</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="发放说明:" prop="remark">
          <el-input v-model="addForm.remark" style="width:100%;" auto-complete="off" placeholder="请输入发放说明">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--详情界面-->
    <el-dialog title="发放详情" v-model="detailFormVisible" :close-on-click-modal="false">
      <el-form :model="detailForm" label-width="100px" ref="detailForm">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放ID:</label>
            <span class="examineFonts">{{detailForm.id}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">发放数量:</label>
            <span class="examineFonts">{{detailForm.totalScore}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放人数:</label>
            <span class="examineFonts">{{detailForm.people}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">发放说明:</label>
            <span class="examineFonts">{{detailForm.remark}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">申请人:</label>
            <span class="examineFonts">{{detailForm.applyer}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">申请时间:</label>
            <span class="examineFonts">{{detailForm.applyTime}}</span>
          </el-col>
        </el-row>
        <el-row v-show="IsApprover">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">审批人:</label>
            <span class="examineFonts">{{detailForm.approver}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">审批时间:</label>
            <span class="examineFonts">{{detailForm.approveTime}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放明细:</label>
            <el-button size="small" type="warning" @click="download(false,detailForm.url)">下载</el-button>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">发放状态:</label>
            <span class="examineFonts">{{detailForm.status}}</span>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="detailFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--审批界面-->
    <el-dialog title="发放审批" v-model="examineFormVisible" :close-on-click-modal="false">
      <el-form :model="examineForm" label-width="100px" ref="detailForm">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放ID:</label>
            <span class="examineFonts">{{examineForm.id}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">发放数量:</label>
            <span class="examineFonts">{{examineForm.totalScore}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放人数:</label>
            <span class="examineFonts">{{examineForm.people}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">发放说明:</label>
            <span class="examineFonts">{{examineForm.remark}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">申请人:</label>
            <span class="examineFonts">{{examineForm.applyer}}</span>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

            <label class="detailLabel">申请时间:</label>
            <span class="examineFonts">{{examineForm.applyTime}}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
            <label class="detailLabel">发放明细:</label>
            <el-button size="small" type="warning" @click="download(false,examineForm.url)">下载</el-button>
          </el-col>
        </el-row>
        <el-row v-show="Isattention">
          <el-col class="detaillabel" style="color:red;padding-left:80px;">
            <!-- <label class="detailLabel" style="color:red;">注:</label> -->
            <span>注:</span>
            <!-- <div style="width:100%;box-sizing:border-box;display:inline-block; position:relative;"> -->
            <span id="attention"></span>
            <a style="color:blue;text-decoration:underline;cursor:pointer;" v-show="contentShow" @click="contentClick">{{contentTitle}}</a>
            <!-- </div> -->
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="examinesubmit" :loading="examineLoading">同意</el-button>
        <el-button @click.native="cancel">拒绝</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
import commons from '../../common/js/common'
import { mapState, mapActions } from 'vuex'
//import NProgress from 'nprogress'
import { listByhand, picURLs, base, beforeApprove, approveActivity } from '../../api/api';

export default {
  data() {
    return {
      picURL: picURLs,
      base: base,
      filters: {
        Time: '',
        status: ''
      },
      Logs: [],
      lists: [],
      fileList: [],
      exportTotal: 0,
      total: 0,
      page: 1,
      pageSize: 10,
      loading: '',
      handworkvalue: '',
      // fullscreenLoading:false,
      Isattention: false,
      listLoading: false,
      addFormVisible: false,
      detailFormVisible: false,
      examineFormVisible: false,
      addLoading: false,
      examineLoading: false,
      contentShow: false,
      sels: [],//列表选中列
      userid: '',
      IsShow: false,
      Isuploads: false,
      IsApprover: false,
      handAdd: false,
      handApprove: false,
      handDetail: false,
      handQuery: false,

      contentTitle: '展开',
      contentAll: '',
      contentPart: '',
      addForm: {
        remark: ''
      },
      detailForm: {

      },
      examineForm: {

      },
      addFormRules: {
        remark: [
          { required: true, message: '请输入发放说明', trigger: 'blur' }
        ]
      }
    }
  },
  computed: mapState([
    'user',
    'winWidth',
    'winHeight'
  ]),
  methods: {
    formatStatus: function (row, column) {
      return row.status == '1' ? '已发放' : (row.status == '2' ? '待审批' : (row.status == '0' ? '审批未通过' : ''));
    },
    formatTime: function (row, column) {
      return commons.getDaytime(row.operationTime, 1, false);
    },
    //脚本
    handleSuccess(response, file, fileList) {
      if (response) {
        if (response.success) {
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.addFormVisible = false;
          this.getGives(true);
        }
        else {
          this.$message({
            message: response.result,
            type: 'error'
          });
        }
        this.addLoading = false;
      }

    },
    Isupload(file, fileList) {
      if (file.status == "ready") {
        this.Isuploads = true;
      }
    },
    //下载
    download: function (bool, url) {
      var protocol = location.protocol;
      var hostname = location.hostname;
      var sUrl = bool ? protocol + '//' + hostname + '/admin-cxb/handScore.xlsx' : this.base + url;
      // var $form = $('<form method="GET"></form>');
      // $form.attr('action', protocol+'//'+hostname+url);
      // $form.attr('https://uat-lm.libertymutual.com.cn'+url);
      // $form.appendTo($('body'));
      // $form.submit();
      // window.open('https://uat-lm.libertymutual.com.cn'+url);
      var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
      var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

      if (isChrome || isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined) {
          //Set HTML5 download attribute. This will prevent file from opening if supported.
          var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
          link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
          var e = document.createEvent('MouseEvents');
          e.initEvent('click', true, true);
          link.dispatchEvent(e);
          return true;
        }
      }

      // Force file download (whether supported by server).
      if (sUrl.indexOf('?') === -1) {
        sUrl += '?download';
      }

      window.open(sUrl, '_self');
      return true;
    },
    //是否显示审批
    IsExamines: function (index, row) {
      if (this.handApprove) {
        if (row.status == "2") {
          return true;
        }
        else {
          return false;
        }      } else {
        return false;
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getGives(true);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getGives(true);
    },
    //获取用户列表
    getGives(bool) {
      let para = new FormData();
      para.append("pageSize", bool ? this.pageSize : this.exportTotal);
      para.append("pageNumber", bool ? this.page : 1);
      para.append("status", this.filters.status);
      para.append("startDate", commons.changeTimes(this.filters.Time, 'start'));
      para.append("endDate", commons.changeTimes(this.filters.Time, 'end'));
      this.listLoading = bool;
      // this.fullscreenLoading = bool?false:true;
      if (!bool) {
        this.loading = this.$loading({
          lock: true,
          text: '正在导出',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      listByhand(para).then((res) => {
        this.lists = res.data.result.content;
        this.total = res.data.result.totalElements;
        this.exportTotal = res.data.result.totalElements;
        this.listLoading = false;
        if (!bool) {
          if (this.exportTotal > 60000) {
            this.$message({
              message: '导出数据量不能超过60000条',
              type: 'error'
            });
          }
          else {
            this.export2Excel();
          }
          this.loading.close();

        }
        else {
          this.Logs = res.data.result.content;
        }
      });
    },
    //table导出excel
    exportExcels: function () {
      this.getGives(false);
    },
    export2Excel: function () {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = ['用户ID', 'IP', '操作模块', '操作内容', '风险等级', '操作时间'];
        const filterVal = ['userId', 'ip', 'module', 'content', 'level', 'operationTime'];
        const list = this.lists;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '日志列表excel');
      })
    },
    formatJson: function (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    //审批权限
    ApproveUser(index,row) {
      var approveAuth = row.approveAuth;
      var userArr = this.user.approve;
      return commons.ApproveUser(approveAuth,userArr);
    },
    configUser() {
      var userArr = this.user.configAuth;
      return !commons.contains(userArr, '1');
    },
    //详情
    handleDetail: function (index, row) {
      this.detailFormVisible = true;
      this.detailForm = Object.assign({}, row);
      if (this.detailForm.status == '1') {
        this.IsApprover = true;
      } else {
        this.IsApprover = false;
      }
      this.detailForm.status = row.status == '1' ? '已发放' : (row.status == '2' ? '待审批' : (row.status == '0' ? '审批未通过' : ''));
    },
    //显示新增界面
    handleAdd: function () {
      var nowTime = Date.parse(new Date());
      this.addFormVisible = true;
      this.Isuploads = false;
      this.fileList = [];
      this.addForm = {
        remark: ''
      };
      this.handworkvalue = 'activity/' + commons.getDaytime(nowTime, 3, false);
    },
    //新增提交
    addSubmit: function () {
      // this.$refs.addForm.validate((valid) => {
      // if (valid) {
      if (this.Isuploads) {
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          this.addLoading = true;
          this.$refs.upload.submit();
        });
      }
      else {
        this.$message({
          message: "请选择发放明细文件",
          type: 'error'
        });
      }
      //   }
      // });
    },
    //审批
    handleExamine: function (index, row) {
      var temp = false;
      this.examineFormVisible = true;
      $('#attention').html('');
      this.contentAll = "";
      this.contentTitle = '展开';
      this.contentPart = "";
      this.examineForm = Object.assign({}, row);
      let para = new FormData();
      para.append('id', this.examineForm.id);
      beforeApprove(para).then((res) => {
        if (res.data.success) {
          let datas = res.data.result;
          if (datas.length > 0) {
            this.Isattention = true;
            for (var i in datas) {
              this.contentAll += '<span>' + datas[i] + '</span><br/>';
              if (i <= 1) {
                this.contentPart += '<span>' + datas[i] + '</span><br/>';
              }
              else {
                temp = true;
              }
            }
            if (temp) {
              $('#attention').html(this.contentPart);
              this.contentShow = true;
            }
            else {
              $('#attention').html(this.contentAll);
              this.contentShow = false;
            }
          }
        }
      });
    },
    //展开，收起
    contentClick() {
      if (this.contentTitle == '展开') {
        this.contentTitle = '收起';
        $('#attention').html('');
        $('#attention').html(this.contentAll);
      }
      else {
        this.contentTitle = '展开';
        $('#attention').html('');
        $('#attention').html(this.contentPart);
      }
    },
    //审批通过
    examinesubmit: function () {
      this.$confirm('确认通过吗？', '提示', {}).then(() => {
        this.examineLoading = true;
        let para = new FormData();
        para.append("id", this.examineForm.id);
        para.append("approveType", "7");
        para.append("type", "yes");
        para.append("remark", "");
        approveActivity(para).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '提交成功',
              type: 'success'
            });
            this.examineFormVisible = false;
            this.getGives(true);
          }
          else {
            this.$message({
              message: res.data.result,
              type: 'error'
            });
          }
          this.examineLoading = false;

        }).catch(() => {
          this.examineLoading = false;
        });
      });
    },
    //审批拒绝
    cancel: function () {
      this.$confirm('确认拒绝吗？', '提示', {}).then(() => {
        this.examineLoading = true;
        let para = new FormData();
        para.append("id", this.examineForm.id);
        para.append("approveType", "7");
        para.append("type", "no");
        para.append("remark", "");
        approveActivity(para).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '提交成功',
              type: 'success'
            });
            this.examineFormVisible = false;
            this.getGives(true);
          }
          else {
            this.$message({
              message: res.data.result,
              type: 'error'
            });
          }
          this.examineLoading = false;

        }).catch(() => {
          this.examineLoading = false;
        });
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    btnShow: function () {
      let thisData = JSON.parse(sessionStorage.getItem('172'));
      let _this = this;
      $.each(thisData, function (i, j) {
        if (thisData[i] == "handAdd") {
          _this.handAdd = true;
        }
        if (thisData[i] == "handApprove") {
          _this.handApprove = true;
        }
        if (thisData[i] == "handDetail") {
          _this.handDetail = true;
        }
        if (thisData[i] == "handQuery") {
          _this.handQuery = true;
        }
      });
    },
  },
  mounted() {
    this.getGives(true);
    this.btnShow();
  }
}

</script>

<style scoped>
.detailLabel {
  /*float:left;*/
  display: inline-block;
  text-align: right;
  width: 120px;
  color: #0b80da;
  font-weight: bold;
}
.detaillabel {
  margin-bottom: 10px;
}
</style>